package game.test.server;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

public class Client {
	private String name;
	private Thread listen;
	private Socket socket;
	private Server server;
	private PrintWriter out;
	private BufferedReader in;
	
	public Client(Socket socket, Server server) {
		this.socket = socket;
		this.server = server;
		
		try {
			out = new PrintWriter(socket.getOutputStream());
			in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private void process(String data) {
		server.process(this, data);
	}
	
	public void setName(String s) {
		name = s;
	}
	
	public void disconnect() {
		server.removeClient(this);
		try {
			in.close();
			out.close();
			socket.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public void send(String data) {
		out.println(data);
	}
	
	public void startListening() {
		listen = new Thread(new Runnable() {
			public void run() {
				while (server.running) {
					try {
						String s = in.readLine();
						if (s != null) {
							process(s);
						}
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		});
		listen.start();
	}
}
